<?php 
namespace app\index\controller;

use app\admin\model\Active;
use app\admin\model\ChoujiangTimes;
use app\admin\model\ContestantNumber;
use app\admin\model\Participant;
use app\admin\model\VisitNumber;
use app\admin\model\VoteList;
use think\Cache;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use think\Loader;
use org\wechat\jssdk; 
use org\phpqrcode\phpqrcode;

class Index extends Controller
{
    protected $session;

    protected $limit = 10;

    protected $pass_way = 'yqsbz';//上班族

    protected $cn_arr = [1=>'一',2=>'二',3=>'三',4=>'四',5=>'五',6=>'六',7=>'七',8=>'八',9=>'九'];

    protected $active;

    protected $phpqrcode;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->session = Session::get('app_item','vote');
        $id=$this->request->param('id');
        $this->active = Cache::get('active_'.$id);

        if(empty($this->active)){
            $active_model = new Active();
            $this->active = $active_model->where('id',$id)->find();
            Cache::set('active_'.$id,$this->active);
        }

        $participant = new Participant();
        $p_count = $participant->where('active_id',$id)->count();
        $p_sum   = $participant->where('active_id',$id)->sum('support');
        $this->assign('p_count',$p_count);
        $this->assign('p_sum',$p_sum);
        $this->assign('type','index');
    }


    protected function before_index(){

        //获取user_agent
        $user_agent = $this->request->header('user-agent');

        $source = 'mobile';
        $url = urlencode($this->request->url(true));
        $jump_url = 'http://mg.5iyq0021.com://pagejump?jump_url='.$url;//
        $error_code = 99;
        //$error_msg = '请在app打开';
        $error_msg = '';

        //微信打开的话跳转到微信控制器
        if(strpos($user_agent, 'MicroMessenger') !== false){
            $this->redirect(url('wx/index',['id'=>$this->request->param('id')],'',true));
            return false;
        }

        //是否为ios设备
        $is_ios=preg_match('/iPhone|iPad|iPod/i',$user_agent) ? 'yes': 'no';

        //app访问则获取用户信息到缓存
        if(strpos($user_agent, 'MAGAPPX') !== false){

            $source = $this->pass_way;
            $info = strstr($user_agent, "MAGAPPX");
            $info=explode("|",$info);

            $token = $this->request->param('token');

            if(!empty($token)){
                $info[7] = $token;
            }
            
            if(empty($info[0])){
                $error_code = 99;
                $error_msg = '请在app打开';
            }elseif (empty($info[7])){
                $error_code = 98;
                $error_msg = '请先登录账号';
            }
            if (!empty($info[3])){
                $jump_url = $info[3].'://pagejump?jump_url='.$url;
            }

                $agent=[
                    "version"=>$info[1],//客户端版本信息
                    "client"=>$info[2],//客户端信息可以获取区分android或ios 可以获取具体机型
                    "site"=>$info[3],  //站点名称
                    "device"=>$info[4],//设备号
                    "sign"=>$info[5],  //签名
                    "signCloud"=>$info[6],//云端签名
                    "token"=>isset($info[7]) ? $info[7] : ""//用户token 用户的token信息
                ];

                //上班族  根据user_id获取当前用户的基本信息
                $res = $this->getCurlData(Config::get('domain.'.$agent['site']).'/mag/cloud/cloud/getUserInfo?token='.$agent['token']
                    .'&secret='.Config::get('secret.'.$agent['site']));

                $res = json_decode($res,true);

               $user_id = isset($res['data']['user_id']) ? $res['data']['user_id'] : "";

            if((empty($this->session) && !empty($info[7])) || $this->session['user_id'] != $user_id){
                if($res['success']){
                    Session::set('app_item',
                        ['user_id'=>$res['data']['user_id'],
                        'name'=>htmlspecialchars($res['data']['name'],ENT_QUOTES),
                        'device'=> $agent['device'],
                        'pass_way'=>$this->pass_way,
                        'site'=>$agent['site'],
                        'phone'=>$res['data']['phone'],
                        'phone_model'=>$agent['client']],
                        'vote');

                    $this->session = ['user_id'=>$res['data']['user_id'],
                        'name'=>htmlspecialchars($res['data']['name'],ENT_QUOTES),
                        'device'=> $agent['device'],
                        'pass_way'=>$this->pass_way,
                        'site'=>$agent['site'],
                        'phone'=>$res['data']['phone'],
                        'phone_model'=>$agent['client'],
                        ];
                }else{
                    $error_msg = $res['msg'];
                }
            }
        }

        $this->assign('type',"index");
        $this->assign('error_code',$error_code);
        $this->assign('error_message',$error_msg);
        $this->assign('source',$source);
        $this->assign('jump_url',$jump_url);
        $this->assign('is_ios',$is_ios);
    }

    protected function render_times($id){
        //获取缓存次数
        $browse_times = Cache::get('browse_time_'.$id);
        if(empty($browse_times)){
            $times_model = new VisitNumber();
            $model = $times_model->where('active_id',$id)->find();
            if(!$model){
                $model = VisitNumber::create([
                    'active_id'=>$id,
                    'times'=>1
                ]);
            }
            $browse_times = $model->times;
            Cache::set('browse_time_'.$id,$model->times);
        }else{
            //Cache::set('browse_time_'.$id,12548);
            //缓存自增
            Cache::inc('browse_time_'.$id);
        }

        //更新到数据库
        $update = Cache::get('update_browse_time_'.$id);
        if(empty($update)){
            Cache::set('update_browse_time_'.$id,1,300);
            $times_model = new VisitNumber();
            $model = $times_model->where('active_id',$id)->find();

            if($model->times < $browse_times){
                $model->times = $browse_times;
                $model->save();
            }else{
                Cache::set('browse_time_'.$id,$model->times);
            }
        }

        $this->assign('times',$browse_times);
    }

    public function index()
    {

        // $user_agent = $this->request->header('user-agent');
        // $info = strstr($user_agent, "MAGAPPX");
        // $info =explode("|",$info);


        $param = $this->request->param();
        $this->before_index();
        
        if(empty($param['id'])){
            return view('public/error',['message'=>'活动id丢失']);
        }

        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,name,is_draw,weight,share_info,template,images,cover,end_img,status,draw_times,btn_info,theme_color,switch_id,is_sign_up,is_reward,reward_limit')
                ->where('id',$param['id'])->find();
        }

        if(!$active){
            return view('public/error',['message'=>'活动不存在']);
        }

        if($active->status != 1){
            return view('public/error',['message'=>'活动未开放']);
        }
        $this->render_times($param['id']);

        $is_draw = $active->is_draw;
        if($is_draw == 1){
            $times = new ChoujiangTimes();
            $times = $times->where('active_id',$param['id'])->where('user_id',$this->session['user_id'])->value('times');
            if($times >= $active->draw_times){
                $is_draw = 0;
            }
        }
        $where = ['active_id'=>['=',$param['id']],'status'=>['=',1]];
        if(!empty($param['keywords'])){
            $where['contestant_number'] = ['exp','="'.$param['keywords'].'" or nickname like "%'.$param['keywords'].'%"'];
        }
        // $order = 'update_time desc';
        // $order_type = 0;
        if(!empty($param['order']) && $param['order']==2){
            $order = 'support desc';
            $order_type = 2;
        }elseif (!empty($param['order']) && $param['order']==1){
            $order = 'create_time desc';
            $order_type = 1;
        }else{
            $order = 'update_time desc';
            $order_type = 99;
        }
        $start = 0;//开始从第一条查询
        $boundary = time();//当前时间
        $participant = new Participant();
        $list = $participant->where($where)->order($order)->limit($start,$this->limit)->select();

        // foreach($list as $keyz => $valz){
        //     //$list[$keyz]['images']['z'] = "123";
        //    var_dump($valz['images2']);
        //    echo "</br>";
        // }
        return view($active->template.'/index/index',
            [
                'active'=>$active,
                'id'=>$param['id'],
                'channel'=>empty($param['channel'])?0:$param['channel'],
                'list'=>$list,
                'keywords'=>empty($param['keywords'])?'':$param['keywords'],
                'count'=>count($list),
                'boundary'=>$boundary.','.$this->limit,
                'order'=>$order_type,
                'se'=>$this->session,
                'is_draw'=>$is_draw,
                'number'=>$active->weight[$this->pass_way],
                'page'=>'index',
                //'site' => 'http://mg.5iyq0021.com'
                'site'=>'magapp',//empty($this->session['site'])?'magapp':Config::get('domain.'.$this->session['site'])

            ]
        );
    }

    public function ajax_list(){
        $param = $this->request->param();
        if(!isset($param['boundary']) && empty($param['boundary'])){
            return json(['code'=>199,'message'=>'参数不完整']);
        }

        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,weight,status')->where('id',$param['id'])->find();
        }

        if(!$active){
            return json(['code'=>199,'message'=>'活动不存在']);
        }

        if($active->status != 1){
            return json(['code'=>199,'message'=>'活动未开放']);
        }

        $array = explode(',',$param['boundary']);
        $boundary = $array[0];
        $start = $array[1];
        $where = ['active_id'=>['=',$param['id']],'status'=>['=',1]];
        if(!empty($param['keywords'])){
            $this->keywords = $param['keywords'];
            $where['contestant_number'] = ['exp','="'.$param['keywords'].'" or nickname like "%'.$param['keywords'].'%"'];
        }
        // $order = 'create_time desc';
        // if(!empty($param['order']) && $param['order']==2){
        //     $order = 'support desc';
        // }

        if(!empty($param['order']) && $param['order']==2){
            $order = 'support desc';
        }elseif (!empty($param['order']) && $param['order']==1){
            $order = 'create_time desc';
        }else{
            $order = 'update_time desc';
        }


        $list = Participant::where($where)->order($order)->limit($start,$this->limit)->select();
        return json([
            'code'=>0,
            'message'=>'成功',
            'data'=>[
                'list'=>$list,
                'number'=>$active->weight[$this->pass_way],
                'count'=>count($list),
                'boundary'=>$boundary.','.($start+$this->limit),
            ]
        ]);
    }

    //报名列表
    public function signup(){
        $param = $this->request->param();
        $error_code = 0;
        $error_msg = '';

        //处理个别情况直接访问参赛者页面
        if(empty($this->session['user_id']) || $this->session['pass_way'] == 'wx'){
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            if (strpos($user_agent, 'MicroMessenger') === false) {
                $error_code = 98;
                $error_msg = '请先登录账号';
            }else{
                $this->redirect(url('Wx/signup',['id'=>$param['id']]));
            }
        }
        $this->assign('error_code',$error_code);
        $this->assign('error_message',$error_msg);

        //判断
        if(empty($param['id'])){
            return view('public/error',['message'=>'活动id丢失']);
        }

        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,name,is_draw,weight,share_info,template,images,business_images,cover,status,act_field,theme_color,shop_name,shop_address,shop_introduction')
                ->where('id',$param['id'])->find();
        }

        if(!$active){
            return view('public/error',['message'=>'活动不存在']);
        }
        //增加访问数
        $this->render_times($param['id']);

        //判断有无参加,若已参加按情况跳转或提示  渲染视图
        $participant = new Participant();
        $participant = $participant->where('user_id',$this->session['user_id'])->where('active_id',$param['id'])->find();

        return view($active->template.'/index/signup',
            [
                'active'=>$active,
                'id'=>$param['id'],
                'keywords'=>'',
                'participant'=>$participant?$participant:null,
                'page'=>'sign_up',
                'site'=>empty($this->session['site'])?'magapp':Config::get('domain.'.$this->session['site'])
            ]);
    }

    public function do_sign_up(){


   
        // $param['id'] = 25;
        // $param['nickname'] = 111;
        // $param['mobile'] = 18658386583;
        // $param['xuanyan'] = 5555;
        // $param['shop_address'] = 3333;
        // $param['shop_introduction'] = 444;
       $this->before_index();

        $param = $this->request->param();
        if(empty($this->session['user_id'])){
            return json(['code'=>504,'message'=>'登录超时']);
        }
        //判断
        if(empty($param['id'])){
            return json(['code'=>196,'message'=>'活动id丢失']);
        }

        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,weight,status,begin_at,end_at')->where('id',$param['id'])->find();
        }

        if($active->is_sign_up != 1){
            return json(['code'=>196,'message'=>'非法操作']);
        }

        if(!$active){
            return json(['code'=>196,'message'=>'活动不存在']);
        }

        if($active->status != 1){
            return json(['code'=>196,'message'=>'活动未开放']);
        }
        //验证活动时效性
        $res = check_active_time($active->begin_at,$active->end_at);
        if($res){
            return json(['code'=>$res['code'],'message'=>$res['message']]);
        }

        //有无参加
        $participant = new Participant();
        //验证信息
        $res = check_params($param);
        if($res){
            return json(['code'=>$res['code'],'message'=>$res['message']]);
        }
        $participant = $participant->where('user_id',$this->session['user_id'])->where('sign_pass_way',$this->pass_way)
            ->where('active_id',$param['id'])->find();

        if(!empty($param['imgs'][0])){
            $imageName = "/25221_".date("His",time())."_".rand(1111,9999).'.jpg';
            $img_dir = "poster/".date("Ymd",time());
            $this->mkdirs($img_dir,0777);
            $this->getImg($param['imgs'][0], $img_dir.$imageName);
            $this->imgzip($img_dir.$imageName,600);
            $imageSrc = "/".$img_dir.$imageName;
        }

        if($participant){
            //return json(['code'=>199,'message'=>'您已经报名参加过活动了']);
            $participant->nickname = empty($param['nickname'])?'':$param['nickname'];
            $participant->mobile = empty($param['mobile'])?'':$param['mobile'];
            $participant->birthday = empty($param['birthday'])?'':$param['birthday'];
            $participant->gender = empty($param['gender'])?'':$param['gender'];
            $participant->xuanyan = empty($param['xuanyan'])?'':$param['xuanyan'];
            $participant->shop_name = empty($param['shop_name'])?'':$param['shop_name'];
            $participant->shop_introduction = empty($param['shop_introduction'])?'':$param['shop_introduction'];
            $participant->shop_address = empty($param['shop_address'])?'':$param['shop_address'];
            $participant->status = 0;
            if(!empty($param['imgs'])){
                $participant->images  = $param['imgs'];
            }
            if(!empty($param['cover'])){
                $participant->cover = $param['cover'];
            }
            $participant->save();
        }else{
            //获取选手编号模型
            $number_model = new ContestantNumber();
            $model = $number_model->where('active_id',$param['id'])->find();

            //添加记录
            Participant::create([
                'active_id'=>$param['id'],
                'user_id'=>$this->session['user_id'],
                'sign_pass_way'=>$this->pass_way,
                'nickname'=>empty($param['nickname'])?'':$param['nickname'],
                'mobile'=>empty($param['mobile'])?'':$param['mobile'],
                'birthday'=>empty($param['birthday'])?'':$param['birthday'],
                'gender'=>empty($param['gender'])?'':$param['gender'],
                'shop_name'=>empty($param['shop_name'])?'':$param['shop_name'],
                'shop_introduction'=>empty($param['shop_introduction'])?'':$param['shop_introduction'],
                'shop_address'=>empty($param['shop_address'])?'':$param['shop_address'],
                'xuanyan'=>empty($param['xuanyan'])?'':$param['xuanyan'],
                'status'=>0,
                'images'=>empty($param['imgs'])?[]:$param['imgs'],
                'images2'=>empty($imageSrc)?'':$imageSrc,
                'cover'=>empty($param['cover'])?'':$param['cover'],
                'channel'=>0,
                'contestant_number'=>$model?$model->number:0,
                'site'=>$this->session['site']
            ]);

            if($model){
                //更新选手编号
                $model->setInc('number', rand(1,3));
            }
        }

        return json(['code'=>0,'message'=>'报名成功']);
    }

    public function do_vote(){

        // $this->session['name'] = 'qqqqww';
        // $this->session['user_id'] = 3953543;
        // $this->session['phone'] = "18658386583";
        // $this->session['device'] = 26;
        // $this->session['site'] = 'yqsbz';
        // $this->session['phone_model'] = '18658386583';
        

        $param = $this->request->param();

        // if(empty($this->session['user_id'])){
        //     return json(['code'=>504,'message'=>'登录超时']);
        // }

        //判断
        if(empty($param['id'])){
            return json(['code'=>196,'message'=>'活动id丢失']);
        }

        $active_model = new Active();
        $active = $active_model->field('id,name,weight,status,begin_at,end_at,limit,limit_param,is_reward,reward_limit,percentage')->where('id',$param['id'])->find();
        //}

        if(!$active){
            return json(['code'=>196,'message'=>'活动不存在']);
        }

        if($active->status != 1){
            return json(['code'=>196,'message'=>'活动未开放']);
        }
        //验证活动时效性
        $end_at = $active->end_at;
        $res = check_active_time($active->begin_at,$end_at);

        if($res){
            return json(['code'=>$res['code'],'message'=>$res['message']]);
        }

        //获取投票信息
        if($this->session['user_id'] == $param['participant_id']){
            return json(['code'=>170,'message'=>'不能自己给自己投票哦~']);
        }
        //循环所选限制方法,将每个方法所需参数分类
        $limit_param = $active->limit_param;
        $ip_info = ip_to_address($this->request->ip());

        $limit_param['user_phone_area'] = get_phone_area($this->session['phone']);
        $limit_param['ip_info']         = $ip_info;
        $limit_param['participant_id']  = $param['participant_id'];
        $limit_param['vote_user_id']    = $this->session['user_id'];
        $limit_param['device_id']       = $this->session['device'];
        $limit_param['active_id']       = $param['id'];
        $limit_param['pass_way']        = $this->pass_way;
        //验证活动投票限制

        $res = check_function($active->limit,$limit_param);

        if($res){
            return json(['code'=>$res['code'],'message'=>$res['message']]);
        }

        $cach_send = $this->cash_send($active,$limit_param['vote_times'],$param['id']);

        $frequency = $cach_send['frequency'];
        $amount    = $cach_send['amount'];
        $vote_success = empty($cach_send['vote_success']) ? '投票成功' : $cach_send['vote_success'];

        // // 是否开启红包
        // $frequency = 999;
        // $amount = 0;

        // if($active->is_reward == 1 && $active->reward_limit > 0){

        //     $VoteList = new VoteList();

        //     $where = ['user_id'        => ['=',$this->session['user_id']],
        //               //'participant_id' => ['=',$param['participant_id']],
        //               'active_id'      => ['=',$param['id']],
        //               //'red_envelopes'  => ['>',0]
        //              ];
        //      $where['create_time'] = ['>',strtotime(date('Y-m-d').' 00:00:00')];

        //      $frequency = $VoteList->where($where)->count();
        //      $amount = 0;
        //      $z      = 0;

        //     //剩余投票数
        //     $surplus = $limit_param['vote_times'] - ($frequency+1);
        //     $vote_success = '投票成功,再投 '.$surplus.' 票即可获得红包';
             
        //     //                                       ($frequency - $params['vote_times']) == 1 // 判断是否为当天最后一次投票
        //     // 是否还有领取次数
        //     if($frequency < $active->reward_limit && ($limit_param['vote_times'] - $frequency) == 1){

        //         // 获奖概率 start
        //         $percentage = json_decode($active->percentage,true);

        //         if(count($percentage) > 0){
        //             foreach($percentage as $key => $val){

        //                 $z = ($val['percentage'] * 100) + $z;

        //                 if($val['percentage'] > 0){
        //                     $val['hb_high'] = $val['hb_high'] * 100;
        //                     $val['hb_low']  = $val['hb_low']  * 100;
        //                     $probability[$z] = $val;

        //                 }
        //             }
        //         }

        //         $rand_amount = mt_rand(1,10000);
        //         foreach($probability as $key => $val){
        //             if($key >= $rand_amount){
        //                 $get_probability = $val;
        //             }
        //         }

        //         $amount = mt_rand($get_probability['hb_low'],$get_probability['hb_high'])/100;

        //         // 获奖概率 end
                
        //         // 红包发放 start
        //         // user_id int 收款用户ID
        //         // amount  float   金额，不可为负数
        //         // remark  string  备注，例如：微商城购买
        //         // out_trade_code  string  业务订单号
        //         // secret  string  后台设置的secret密钥

        //         $secret  = $this->session['site'];
        //         $user_id = $this->session['user_id'];
        //         $remark  = "投票红包";
        //         $out_trade_code = time();

        //         $this->getCurlData(Config::get('domain.'.$secret)."/core/pay/pay/accountTransfer?user_id={$user_id}&amount={$amount}&remark={$remark}&out_trade_code={$out_trade_code}&secret=".Config::get('secret.'.$secret));
        //         // 红包发放 end
                
        //     }else{
        //         $frequency = 999;
        //     }
        // }

        //添加投票记录
        $res = VoteList::create([
            'active_id'=>$active->id,
            'participant_id'=>$param['participant_id'],
            'user_id'=>$this->session['user_id'],
            'nickname'=>$this->session['name'],
            'from_ip'=>$ip_info['ip'].$ip_info['message'],
            'from_device'=>$this->session['device'],
            'from_pass_way'=>$this->pass_way,
            'create_time'=>time(),
            'channel'=>0,
            'site'   =>$this->session['site'],
            'phone' => $this->session['phone'],
            'phone_area' => get_phone_area($this->session['phone']),
            'phone_model' => $this->session['phone_model'],
            'red_envelopes' => $amount,
        ]);

        if($res){
            
            //更新被投票人的数据
            $participant = new Participant();
            if($participant->where('active_id',$active->id)->where('user_id',$param['participant_id'])
                ->inc('pass_way_yqsbz')->inc('support',$active->weight[$this->pass_way])->update(['update_time'=>time()])){
                return json(['code'=>0,'message'=>$vote_success,'frequency' => $frequency,  'reward_limit' => $active->reward_limit, 'amount' => $amount, 'support'=>$active->weight[$this->pass_way]]);
            }
        }
        return json(['code'=>199,'message'=>'投票失败','support'=>0]);
    }


    public function detail(){

        $param = $this->request->param();
        //获取访问人ID信息
        $is_self = 0;
        $user_id = empty($param['user_id'])?'':$param['user_id'];
        if(empty($user_id)){
            $user_id = $this->session['user_id'];
            $is_self = 1;
        }

        //处理个别情况直接访问参赛者页面
        if(empty($this->session['user_id']) || $this->session['pass_way'] == 'wx'){
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            if (strpos($user_agent, 'MicroMessenger') !== false) {
                $this->redirect(url('Wx/detail',['id'=>$param['id'],'user_id'=>$user_id]));
            }
        }

        //判断
        if(empty($param['id'])){
            return view('public/error',['message'=>'活动id丢失']);
        }

        //增加访问数
        $this->render_times($param['id']);
        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,name,is_draw,weight,share_info,template,images,business_images,cover,status,draw_times')
                ->where('id',$param['id'])->find();
        }

        if(!$active){
            return view('public/error',['message'=>'活动不存在']);
        }

        if($active->status != 1){
            return view('public/error',['message'=>'活动未开放']);
        }


        //查询有无报名
        $participant = new Participant();
        $info = $participant->where('user_id',$user_id)->where('active_id',$param['id'])->find();

        //根据情况渲染视图
        if($info){
            switch ($info->status){
                case 0:
                    $no = '未审核';
                    break;
                case 1:
                    $no = $participant->where('active_id',$param['id'])->where('status',1)->where('support','>=',$info->support)
                        ->order('support desc,create_time asc')->count();
                    $no = '第'.$no.'名';
                    break;
                default:
                    $no = '审核未通过';
            }

            $is_draw = $active->is_draw;
            if($is_draw == 1){
                $times = new ChoujiangTimes();
                $times = $times->where('active_id',$param['id'])->where('user_id',$this->session['user_id'])->value('times');
                if($times >= $active->draw_times){
                    $is_draw = 0;
                }
            }
            return view($active->template.'/index/detail',
                [
                    'active'=>$active,
                    'id'=>$param['id'],
                    'record'=>$info,
                    'is_self'=>$is_self,
                    'no'=>$no,
                    'se'=>$this->session,
                    'is_draw'=>$is_draw,
                    'keywords'=>'',
                    'page'=>'',
                    'number'=>$this->cn_arr[$active->weight[$this->pass_way]],

                ]);
        }else{
            if($is_self){
                $message = '您还没有报名';
                $url = url('index',['id'=>$param['id']]);
                $this->redirect('signup',['id'=>$param['id']]);
            }else{
                $message = '报名人状态异常';
                $url = url('index/index',['id'=>$param['id']]);
            }
            return view('public/error',['message'=>$message,'url'=>$url]);
        }
    }

    public function intro(){
        $param = $this->request->param();
        //判断
        if(empty($param['id'])){
            return view('public/error',['message'=>'活动id丢失']);
        }
        //增加访问数
        $this->render_times($param['id']);
        $active = $this->active;
        if(empty($active)){
            $active_model = new Active();
            $active = $active_model->field('id,name,is_draw,share_info,template,images,cover,status,intro')->where('id',$param['id'])->find();
        }

        if(!$active){
            return view('public/error',['message'=>'活动不存在']);
        }

        if($active->status != 1){
            return view('public/error',['message'=>'活动未开放']);
        }
        return view($active->template.'/index/intro',
            [
                'active'=>$active,
                'id'=>$param['id'],
                'keywords'=>'',
                'page'=>'intro'
            ]
        );
    }

    private function getCurlData($url,$post_data=[]){
        $ch = curl_init() or die (curl_error());
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置post访问
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);//响应时间
        $get = curl_exec($ch);
        curl_close($ch);
        return $get;
    }

    public function poster()
    {

            $id = $this->request->param('id');
            $playerid = $this->request->param('playerid');
            $active_model = new Participant();
            $active = $active_model->field('id,user_id,active_id,contestant_number,nickname,xuanyan,images,images2,qrcode')->where('contestant_number',$playerid)->where('active_id',$id)->find();      

            if(empty($active->qrcode)){

               // $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
               
                $url = 'http://'.$_SERVER['HTTP_HOST']."/index.php/index/wx/detail/id/".$id."/channel_id/0.html?user_id=".$active->user_id;

                $qrcode_name = time().mt_rand(1,10000);

                $dir_url = "poster/".date("Ymd",time());
                $qrcode_url = "http://{$_SERVER['HTTP_HOST']}/".$dir_url."/{$qrcode_name}.png";

                $this->mkdirs($dir_url,0777);
                $active_model->where('contestant_number',$playerid)->where('active_id',$id)->update(['qrcode' => $qrcode_url]);
                Phpqrcode::png($url,$dir_url."/".$qrcode_name.".png",0,3,4);

            }else{
                $qrcode_url = $active->qrcode;
            }

            return view('default/index/poster',['message'=>'海报','active'=>$active,'url' => $qrcode_url]);
    }

    public function poster_img()
    {
            $param = $this->request->param();


// $param['active_id'] =  25;
// $param['base64']    =  "…a0AgP4KNQMH1Oir3kNfJSDAeBIwWObBULkn+govBstExagAATdxabjcjWvlbqYLwRIALDf/yut/gaPowF8GAKPFLowUOkkRIadlACAkloqdVgCAfHxrtNjO5DsBC05Sht9VkrNk7D0MbTrSJePJClemKt2ZqnQ3Mv5uyjRgotyJyQpnJivEFV459jNS6shIibNJVafxFGC8wl1pSxo7IGBAvtQrm/7xCo8Vf8uLv3L8R4aAz0pdGSl1Z6zCEO2RTb4MAJ8f9maiytMkJjRaIfY3hkucGSpyRF/spMDGrWpvSSpuHPZkus6b6SNqvmjwYabZn3kp/3/nwzDm2oK5d1rDPzojWOyMYuFMBH/viOBepwCBu2c0LJ7Xcr97Cw8ubOWBkflXdgIux3J/BQQIAFgOAULC+CtaZv6VKcCnAgKMAeBJXxJP+xMlCEjg2WAi3w6nKADwYiSVl2M7+W48zaCJHf8VAl5dT+M/+Xixm5BaSKEAAAAASUVORK5CYII=";
//  $param['contestant_number']  = 46;
//  $param['template']           =  'whdz';


            $image=$param['base64'];

            $active_model = new Participant();
            $active = $active_model->field('id,contestant_number,nickname,xuanyan,images,qrcode,poster')->where('contestant_number',$param['contestant_number'])->where('active_id',$param['active_id'])->find();

            if(!empty($active->poster)){
                $poster = explode("/",$active->poster);
                $imageName=$poster[3];
            }else{
                $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.png';
            }

            
            if (strstr($image,",")){
                $image = explode(',',$image);
                $image = $image[1];
            }

            $path = "poster/".date("Ymd",time());
            if (!is_dir($path)){ //判断目录是否存在 不存在就创建
                mkdir($path,0777,true);
            }
            $imageSrc=  ROOT_PATH ."public/".$path."/". $imageName;  //图片名字

             $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
             $this->scalePic($imageSrc,400,400);
             
            if (!$r) {
                return json(['data'=>null,"code"=>1,"message"=>"图片生成失败"]);
            }
            // else{
            //     return json(['data'=>1,"code"=>0,"message"=>"图片生成成功"]);
            // }

        $waterImg['works']  = ROOT_PATH ."public/".$path."/". $imageName;
        $waterImg['qrcode'] = $active->qrcode;

        $waterImg['text']   = array(
                                    "大家好，我们是",
                                    $active->contestant_number."号 ".$active->nickname,
                                    "我们的口号是：",
                                    $active->xuanyan
                                   );

        $this->img_water_mark("index/files/poster-bg.jpg", $waterImg, ROOT_PATH ."public/".$path, $imageName, $positon=5, $alpha=100);

        $active_model->where('contestant_number',$param['contestant_number'])->where('active_id',$param['active_id'])->update(['poster' => "/".$path."/". $imageName]);
        
        $img_src =  'http://'.$_SERVER['HTTP_HOST']."/".$path."/". $imageName;
        return json(['data'=>1,"code"=>0, "message"=>$img_src]);

    }


/**
 * 图片加水印(适用于png/jpg/gif格式)
 * 
 * @author flynetcn
 *
 * @param $srcImg 原图片
 * @param $waterImg 水印图片
 * @param $savepath 保存路径
 * @param $savename 保存名字
 * @param $positon 水印位置 
 * 1:顶部居左, 2:顶部居右, 3:居中, 4:底部局左, 5:底部居右 
 * @param $alpha 透明度 -- 0:完全透明, 100:完全不透明
 * 
 * @return 成功 -- 加水印后的新图片地址
 *     失败 -- -1:原文件不存在, -2:水印图片不存在, -3:原文件图像对象建立失败-4:水印文件图像对象建立失败, -5:加水印后的新图片保存失败
 */
function img_water_mark($srcImg, $waterImg, $savepath=null, $savename=null, $positon=5, $alpha=30)
{
  $temp = pathinfo($srcImg);
  $name = $temp['basename'];
  $path = $temp['dirname'];
  $exte = $temp['extension'];
  $savename = $savename ? $savename : $name;
  $savepath = $savepath ? $savepath : $path;
  $savefile = $savepath .'/'. $savename;
  $srcinfo = @getimagesize($srcImg);

  if (!$srcinfo) {
    return -1; //原文件不存在
  }
  // $waterinfo = @getimagesize($waterImg);
  // if (!$waterinfo) {
  //   return -2; //水印图片不存在
  // }
  
   $srcImgObj = $this->image_create_from_ext($srcImg);

  foreach($waterImg as $key=>$val){

    $waterinfo = @getimagesize($val);
    if($key == 'works'){
        $works = $this->image_create_from_ext($val);
        $works_x = ($srcinfo[0]-$waterinfo[0])/2+0; $works_y = ($srcinfo[1]-$waterinfo[1])/2-100;
        imagecopymerge($srcImgObj, $works, $works_x, $works_y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
    }

    if($key == 'qrcode'){
        $qrcode = $this->image_create_from_ext($val);
        $qrcode_x = $srcinfo[0]-$waterinfo[0]-370; $qrcode_y = $srcinfo[1]-$waterinfo[1]-110;
        imagecopymerge($srcImgObj, $qrcode, $qrcode_x, $qrcode_y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
    }

    if($key == 'text'){
        $hb     = imagecolorallocate($srcImgObj,0,0,0);
        $hb_red = imagecolorallocate($srcImgObj,255,0,0);
        $h = 620;
        foreach($val as $k => $v){
            $h += 30;

            if($k == 2){
                imagettftext($srcImgObj,14,0,110,$h,$hb_red,"index/files/yahei.ttf",$v); //加水印
            }elseif($k == 1){
                imagettftext($srcImgObj,20,0,110,$h,$hb,"index/files/yahei.ttf",$v); //加水印
            }else{
                imagettftext($srcImgObj,16,0,110,$h,$hb,"index/files/yahei.ttf",$v); //加水印
            }
        }
    }
  }


     

      // if (!$srcImgObj) {
      //   return -3; //原文件图像对象建立失败
      // }
     // $waterImgObj = $this->image_create_from_ext($waterImg);
      // if (!$waterImgObj) {
      //   return -4; //水印文件图像对象建立失败
      // }
      // switch ($key) {
      // //1顶部居左
      // case 1: $x=$y=0; break;
      // //2顶部居右
      // case 2: $x = $srcinfo[0]-$waterinfo[0]; $y = 0; break;
      // //3居中
      // case works: $works_x = ($srcinfo[0]-$waterinfo[0])/2; $works_y = ($srcinfo[1]-$waterinfo[1])/2; break;
      // //4底部居左
      // case 4: $x = 0; $y = $srcinfo[1]-$waterinfo[1]; break;
      // //5底部居右
      // case qrcode: $x = $srcinfo[0]-$waterinfo[0]-70; $y = $srcinfo[1]-$waterinfo[1]-150; break;
      // default: $x=$y=0;
      // }

      // imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
      // imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
      // imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);

  switch ($srcinfo[2]) {
      case 1: imagegif($srcImgObj, $savefile); break;
      case 2: imagejpeg($srcImgObj, $savefile); break;
      case 3: imagepng($srcImgObj, $savefile); break;
      default: return -5; //保存失败
  }

    imagedestroy($srcImgObj);
    imagedestroy($qrcode);
    imagedestroy($works);
  return $savefile;
}



function image_create_from_ext($imgfile)
{
  $info = getimagesize($imgfile);

  $im = null;
  switch ($info[2]) {
  case 1: $im=imagecreatefromgif($imgfile); break;
  case 2: $im=imagecreatefromjpeg($imgfile); break;
  case 3: $im=imagecreatefrompng($imgfile); break;
  }
  return $im;
}




/**
 * @function 等比缩放函数(以保存的方式实现)
 * @param string $picname 被缩放的处理图片源
 * @param int $maxX 缩放后图片的最大宽度
 * @param int $maxY 缩放后图片的最大高度
 * @param string $pre 缩放后图片名的前缀名
 * @return string 返回后的图片名称(带路径),如a.jpg --> s_a.jpg
 */
function scalePic($picname,$maxX=100,$maxY=100,$pre='')
{
    $info = getimagesize($picname); //获取图片的基本信息
    $width = $info[0];//获取宽度
    $height = $info[1];//获取高度
    //判断图片资源类型并创建对应图片资源
    $im = $this->getPicType($info[2],$picname);
    //计算缩放比例
    $scale = ($maxX/$width)>($maxY/$height)?$maxY/$height:$maxX/$width;
    //计算缩放后的尺寸
    $sWidth = floor($width*$scale);
    $sHeight = floor($height*$scale);
    //创建目标图像资源
    $nim = imagecreatetruecolor($sWidth,$sHeight);
    //等比缩放
    imagecopyresampled($nim,$im,0,0,0,0,$sWidth,$sHeight,$width,$height);
    //输出图像
    $newPicName = $this->outputImage($picname,$pre,$nim);
    //释放图片资源
    imagedestroy($im);
    imagedestroy($nim);
    return $newPicName;
}

/**
 * function 判断并返回图片的类型(以资源方式返回)
 * @param int $type 图片类型
 * @param string $picname 图片名字
 * @return 返回对应图片资源
 */
function getPicType($type,$picname)
{
    $im=null;
    switch($type)
    {
        case 1:  //GIF
            $im = imagecreatefromgif($picname);
            break;
        case 2:  //JPG
            $im = imagecreatefromjpeg($picname);
            break;
        case 3:  //PNG
            $im = imagecreatefrompng($picname);
            break;
        case 4:  //BMP
            $im = imagecreatefromwbmp($picname);
            break;
        default:
            die("不认识图片类型");
            break;
    }
    return $im;
}

/**
 * function 输出图像
 * @param string $picname 图片名字
 * @param string $pre 新图片名前缀
 * @param resourse $nim 要输出的图像资源
 * @return 返回新的图片名
 */
function outputImage($picname,$pre,$nim)
{
    $info = getimagesize($picname);
    $picInfo = pathInfo($picname);
    $newPicName = $picInfo['dirname'].'/'.$pre.$picInfo['basename'];//输出文件的路径
    switch($info[2])
    {
        case 1:
            imagegif($nim,$newPicName);
            break;
        case 2:
            imagejpeg($nim,$newPicName);
            break;
        case 3:
            imagepng($nim,$newPicName);
            break;
        case 4:
            imagewbmp($nim,$newPicName);
            break;
    }
    return $newPicName;
}

    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }

    function getImg($url = "", $filename = "") {
        if(is_dir(basename($filename))) {
            echo "The Dir was not exits";
            return false;
        }
        //去除URL连接上面可能的引号

        $hander = curl_init();
        $fp = fopen($filename,'wb');
        curl_setopt($hander,CURLOPT_URL,$url);
        curl_setopt($hander,CURLOPT_FILE,$fp);
        curl_setopt($hander,CURLOPT_HEADER,0);
        curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
        //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
        curl_setopt($hander,CURLOPT_TIMEOUT,60);
        /*$options = array(
            CURLOPT_URL=> '/thum-f3ccdd27d2000e3f9255a7e3e2c4880020110622095243.jpg',
            CURLOPT_FILE => $fp,
            CURLOPT_HEADER => 0,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_TIMEOUT => 60
        );
        curl_setopt_array($hander, $options);
        */
        curl_exec($hander);
        curl_close($hander);
        fclose($fp);
        return  true;
    }

    function imgzip($src,$newwid){
        $imgInfo = getimagesize($src);

        $imgType = image_type_to_extension($imgInfo[2], false);

        $fun = "imagecreatefrom{$imgType}";

    //声明图片   打开图片 在内存中
        $image = $fun($src);
    //方便配置长度宽度、高度，设置框为变量wid,高度为hei
        $wid=$imgInfo[0];
        $hei=$imgInfo[1];
    //判断长度和宽度，以方便等比缩放,规格按照500, 320

        if($wid <= 600){
            return true;
        }
        $wid_b = $newwid/$wid;
        $wid = $newwid;
        $hei=floor($hei*$wid_b);

    //在内存中建立一张图片
        $images2 = imagecreatetruecolor($wid, $hei); //建立一个500*320的图片

    //将原图复制到新建图片中
    //imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)

        imagecopyresampled($images2, $image, 0, 0, 0, 0, $wid,$hei, $imgInfo[0],$imgInfo[1]);

    //销毁原始图片
        imagedestroy($image);


    //直接输出图片文件

        // header("Content-type: ".$imgInfo['mime']);
        // imagejpeg($images2);

    //保存图片 到新文件
        imagejpeg($images2, $src, 100); //10代码输出图片的质量 0-100 100质量最高

    //销毁
        imagedestroy($images2);
    }


    public function cash_send($active,$vote_times,$active_id){

         // 是否开启红包
            $frequency = 999;
            $amount = 0;

            if($active->is_reward == 1 && $active->reward_limit > 0){

                $VoteList = new VoteList();

                $where = ['user_id'        => ['=',$this->session['user_id']],
                          //'participant_id' => ['=',$param['participant_id']],
                          'active_id'      => ['=',$active_id],
                          //'red_envelopes'  => ['>',0]
                         ];
                 $where['create_time'] = ['>',strtotime(date('Y-m-d').' 00:00:00')];

                 $frequency = $VoteList->where($where)->count();
                $z      = 0;

                //剩余投票数
                $surplus = $vote_times - ($frequency+1);
                $vote_success = '投票成功,再投 '.$surplus.' 票即可获得红包';
                 
                //                                       ($frequency - $params['vote_times']) == 1 // 判断是否为当天最后一次投票
                // 是否还有领取次数
               if($frequency < $active->reward_limit && ($vote_times - $frequency) == 1){

                    // 获奖概率 start
                    $percentage = json_decode($active->percentage,true);

                    if(count($percentage) == 0){
                       return false;
                    }

                    foreach($percentage as $key => $val){

                        $z = ($val['percentage'] * 100) + $z;
                        if($val['percentage'] > 0){
                            $val['hb_high'] = $val['hb_high'] * 100;
                            $val['hb_low']  = $val['hb_low']  * 100;
                            $probability[$z] = $val;
                        }
                    }
                    
                    $rand_amount = mt_rand(1,10000);
                    foreach($probability as $key => $val){
                        if($key >= $rand_amount && !isset($get_probability)){
                            $get_probability = $val;
                            break;
                        }
                    }
                    $amount = mt_rand($get_probability['hb_low'],$get_probability['hb_high'])/100;
                    // 获奖概率 end
                    
                    // 红包发放 start
                    // user_id int 收款用户ID
                    // amount  float   金额，不可为负数
                    // remark  string  备注，例如：微商城购买
                    // out_trade_code  string  业务订单号
                    // secret  string  后台设置的secret密钥

                    $secret  = $this->session['site'];
                    $user_id = $this->session['user_id'];
                    $remark  = "投票红包";
                    $out_trade_code = time();

                    $this->getCurlData(Config::get('domain.'.$secret)."/core/pay/pay/accountTransfer?user_id={$user_id}&amount={$amount}&remark={$remark}&out_trade_code={$out_trade_code}&secret=".Config::get('secret.'.$secret));
                    // 红包发放 end
                    
                }else{
                    $frequency = 999;
                }
           }

            return array("amount"=>$amount, "frequency"=>$frequency,"vote_success"=>isset($vote_success) ? $vote_success : "");
    }

}
